//
//  WCNViewController.m
//  WCN
//
//  Created by 杨鑫 on 15/5/29.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNViewController.h"
//
#import "WCButton.h"
//
#import "UINavigationItem+Offset.h"
#import "Macros.h"
#import "NoRecordsView.h"
static CGFloat aqiConnectH = 20;

@interface WCNViewController ()

@property(nonatomic, strong)UILabel *connectLabel;
@property(nonatomic, assign)BOOL connect;
@property(nonatomic, assign)NSInteger isFirstRefresh;
@property(nonatomic, strong)UIActivityIndicatorView *activityView;
@end

@implementation WCNViewController

#pragma mark - Life Circle

- (instancetype)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
    self = [super initWithNibName:nibName bundle:nibBundle];
    if (self) {
        #warning 在控制器init方法中，不要访问视图，不然会提前调用viewDidLoad方法
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //判断是否是topController，或者是模态视图的topController
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            if (self.presentingViewController) {
                //need pageBack
                WCButton *closeButton = [WCButton closeButton];
                [closeButton addTarget:self action:@selector(closePage) forControlEvents:UIControlEventTouchUpInside];
                [self.navigationItem addLeftBarButtonItem:closeButton];
            }
        } else {
            //need pageBack
            WCButton *backButton = [WCButton backButton];
            [backButton addTarget:self action:@selector(pageBack) forControlEvents:UIControlEventTouchUpInside];
            [self.navigationItem addLeftBarButtonItem:backButton];
        }
    }
    _connect = YES;
//    [self observeNetworkStatus];
}
- (void)loadNOrecodView:(UITableView *)tableView dataArray:(NSArray *)dataArray
{
    if (dataArray.count == 0) {
        tableView.tableHeaderView = [[NoRecordsView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        
    }else{
        tableView.tableHeaderView =nil;
    }
    
}

- (void)footerAddBtnWith:(NSString *)title{
    
    UIButton *footerBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    footerBtn.frame =CGRectMake(30, kScreenHeight -35-65, kScreenWidth -60, 35);
    [footerBtn setTitle:title forState:UIControlStateNormal];
    [footerBtn setBackgroundColor:HexRGB_WSJ(84, 130, 255)];
    footerBtn.layer.cornerRadius = 5;
    footerBtn.layer.masksToBounds= YES;
    footerBtn.tag = 900;
    [footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [footerBtn addTarget:self action:@selector(footerAddBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:footerBtn];
}
#pragma mark - Target Actions

- (void)closePage
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)pageBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Setter

- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
    
    if (self.titleLabel) {
        self.titleLabel.text = title;
    } else {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 30)];
//        titleLabel.backgroundColor =[UIColor redColor];
        titleLabel.text = title;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont boldSystemFontOfSize:20];
        
        self.navigationItem.titleView = titleLabel;
        self.titleLabel = titleLabel;
    }
//    self.navigationItem.titleView = [self customTitleView];
}
- (void)addRightBarButtonItemWithTitle:(NSString *)title target:(id)target action:(SEL)action{
                UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:target action:action];
    
    self.navigationItem.rightBarButtonItem = item;;

}
- (void)addRightBarButtonItemWithImage:(NSString *)imageName  target:(id)target action:(SEL)action
{
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageName] style:UIBarButtonItemStylePlain target:target action:action];
     self.navigationItem.rightBarButtonItem = item;

}


// 标题视图
- (UIView *)titleView
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 8, 14, 14)];
    imageView.translatesAutoresizingMaskIntoConstraints = NO;
    imageView.image = [UIImage imageNamed:@"Patient_Title"];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    self.titleLabel = titleLabel;
    titleLabel.tag = 900;
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    
    UIView *view = [[UIView alloc] init];
    view.translatesAutoresizingMaskIntoConstraints = NO;
    [view addSubview:imageView];
    [view addSubview:titleLabel];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:nil attribute:NSLayoutAttributeNotAnAttribute
                                                    multiplier:1 constant:30]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:view attribute:NSLayoutAttributeLeading
                                                    multiplier:1 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeTrailing
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:view attribute:NSLayoutAttributeTrailing
                                                    multiplier:1 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterY
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:view attribute:NSLayoutAttributeCenterY
                                                    multiplier:1 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeCenterY
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:imageView attribute:NSLayoutAttributeCenterY
                                                    multiplier:1 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:imageView attribute:NSLayoutAttributeTrailing
                                                    multiplier:1 constant:0]];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 118, 30)];
    [titleView addSubview:view];
    [titleView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:titleView attribute:NSLayoutAttributeCenterX
                                                         multiplier:1 constant:0]];
    [titleView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterY
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:titleView attribute:NSLayoutAttributeCenterY
                                                         multiplier:1 constant:0]];
    
    UIButton *showPatientDetail = [[UIButton alloc] initWithFrame:titleView.bounds];
    [showPatientDetail addTarget:self action:@selector(clickTitleView) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:showPatientDetail];
    //titleView.backgroundColor = [UIColor blueColor];
    
    return titleView;
}

//通用标题
- (UIView *)customTitleView {
    
    _isFirstRefresh = 0;
    UIView *customTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    
    // Use autoresizing to restrict the bounds to the area that the titleview allows
    customTitleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    customTitleView.autoresizesSubviews = YES;
    customTitleView.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
//    titleLabel.backgroundColor = [UIColor blueColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textAlignment = NSTextAlignmentCenter;
//    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//    titleLabel.autoresizingMask = customTitleView.autoresizingMask;
    titleLabel.text = self.title;
    self.titleLabel = titleLabel;
    CGRect leftViewbounds = self.navigationItem.leftBarButtonItem.customView.bounds;
    CGRect rightViewbounds = self.navigationItem.rightBarButtonItem.customView.bounds;
    CGFloat maxWidth = leftViewbounds.size.width > rightViewbounds.size.width ? leftViewbounds.size.width : rightViewbounds.size.width;
    maxWidth += 15;//leftview 左右都有间隙，左边是5像素，右边是8像素，加2个像素的阀值 5 ＋ 8 ＋ 2
    NSString *text = self.title;
    

    CGFloat textWidth = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:20]}].width;

    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] init];
    [activityView startAnimating];
    _activityView = activityView;
    activityView.hidesWhenStopped = YES;
    activityView.color = [UIColor grayColor];
    titleLabel.frame = CGRectMake(44, 0, textWidth, 44);
    //标题居中
    if ((kScreenWidth - maxWidth - textWidth)/2 > 44) {
        titleLabel.center = CGPointMake((kScreenWidth - maxWidth * 2)/2  - 44 , 22);
    }
    [activityView setFrame:CGRectMake(CGRectGetMinX(titleLabel.frame) - 44, 0, 44, 44)];
    customTitleView.frame = CGRectMake(0, 0, kScreenWidth - maxWidth * 2, 44);
    [customTitleView addSubview:titleLabel];
    [customTitleView addSubview:activityView];
//    self.navigationItem.titleView = customTitleView;
    return customTitleView;
}

- (void)refreshing:(BOOL)refresh {
//    if (self.isFirstRefresh <= 1) {
//        if (_activityView) {
            if (refresh) {
                [_activityView startAnimating];
            }else {
                [_activityView stopAnimating];
            }
            //_isFirstRefresh++;
//        }
//    }
}

- (void)clickTitleView
{
    NSLog(@"super clickTitleView");
}


- (void)observeNetworkStatus{
    
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable) {
            [self disPlayConnecting];
//            [self alertMessage:@"你现在的网络不可用，无法进行视频会议"];
            //self.netStatus = NetworkStatusNO;
        }else {
            [self disPlayConnected];
            //            self.netStatus = NetworkStatusUnknow;
        }
    }];
}

- (UILabel *)connectLabel {

    if (!_connectLabel) {
        _connectLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -aqiConnectH, kScreenWidth, aqiConnectH)];
        _connectLabel.textAlignment = NSTextAlignmentCenter;
        _connectLabel.textColor = [UIColor whiteColor];
        [self.view addSubview:_connectLabel];
    }
    return _connectLabel;
}

//显示正在连接。。。
- (void)disPlayConnecting {
    
    if (!self.connect) {
        return;
    }
    
    self.connectLabel.backgroundColor = [UIColor brownColor];
    self.connectLabel.text = @"连接中...";
        [UIView animateWithDuration:0.3 animations:^{
            UIView *view = self.view;
            CGRect frame = view.frame;
            frame.origin.y += aqiConnectH;
            frame.size.height -= aqiConnectH;
            view.frame = frame;
            self.connect = NO;
        }];
}

//显示网络已连接
- (void)disPlayConnected {
    
    if (self.connect) {
        return;
    }
    
    self.connectLabel.backgroundColor = [UIColor blueColor];
    self.connectLabel.text = @"已连接...";
    [UIView animateWithDuration:0.3 delay:1 options:0 animations:^{
        
        UIView *view = self.view;
        CGRect frame = view.frame;
        frame.origin.y -= aqiConnectH;
        frame.size.height += aqiConnectH;
        view.frame = frame;
        self.connect = YES;
    } completion:^(BOOL finished) {
        
    }];
  
    
}


//    WCButton *logoutBtn = [WCButton txtButton:@"注销" frame:CGRectMake(0, 0, 44, 30)];
//    [logoutBtn setTitleColor:HexRGB(0xe91114)];
//    [logoutBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationItem addRightBarButtonItem:logoutBtn];
@end
